
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from './model/routes'
import store from '@/store'
import { isNullOrUndefind, JsonExcludeNullOrUndefind } from '@/utils/utils'
import { isrememberLogin } from '@/api/customer'

// 路由守卫

const router = new VueRouter({
  routes
})

// 前置路由守卫
router.beforeEach((to, from, next) => {
  let customer = window.sessionStorage.getItem('customer')
  let account = window.sessionStorage.getItem('account')
  // console.log(customer+'###'+account)
if(isNullOrUndefind(customer)&&isNullOrUndefind(account)){
  // console.log('你好');
  next()
  return
}
 customer = window.localStorage.getItem('customer')
 account = window.localStorage.getItem('account')
if(isNullOrUndefind(customer)&&isNullOrUndefind(account)){
  isrememberLogin(JSON.parse(customer), JSON.parse(account)).then(res => {
    // console.log('记住')
   if(!isNullOrUndefind(res.customer)||!isNullOrUndefind(res.customer)){
        let list = store.state.dynamicrouter.needLoginRouterList
      const path = to.path
      if (list.length === 0) {
        store.dispatch('dynamicrouter/getneedLoginRouterList')
        setTimeout(function () {
          list = store.state.dynamicrouter.needLoginRouterList
          //   console.log(list)
          //    console.log(path)
          // console.log(isNeedLogin(list,path))
          if (!isNeedLogin(list, path)) {
            next();
          } else {
           
            next(from)
            alert('需要登录才能操作 请先登录');
          }
          // console.log('wdefrv')
        }, '100')
      }
      if (list.length > 0) {
    if (!isNeedLogin(list, path)) {
      next();
    } else {
    
      next(from)
      alert('需要登录才能操作 请先登录')
    }
 return
  }
   }else{
    next();
    return
   }
  })
}else {
  let list = store.state.dynamicrouter.needLoginRouterList
  const path = to.path
  if (list.length === 0) {
    store.dispatch('dynamicrouter/getneedLoginRouterList')
    setTimeout(function () {
      list = store.state.dynamicrouter.needLoginRouterList
      //   console.log(list);
      //    console.log(path)
      // console.log(isNeedLogin(list,path))
      if (!isNeedLogin(list, path)) {
        next();
      } else {
        alert('需要登录才能操作 请先登录');
        next(from)
      }
      // console.log('wdefrv')
    }, '100')
  }
  if (list.length > 0) {
    if (!isNeedLogin(list, path)) {
      next();
    } else {
      alert('需要登录才能操作 请先登录')
      next(from)
  
    }
  }
}
  /**
   * 判断路由是否需要登录
   * @param {} params 
   */
  function isNeedLogin(list, path) {
    if (list.length === 0) return false;
    if (list.filter(li => li === path).length > 0) return true;
    if (list.filter(li => path.indexOf(li) === 0 && (path.substr(li.length, 1) === '' || path.substr(li.length, 1) === '/')).length > 0) return true;
    return false;
  }
})
//后置路由守卫
router.afterEach((to, from) => {

})
export default router;
